package network_programming.np1_socket_and_serversocket;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketDemoSender {
    private String host = "localhost";
    private int port = 8081;
    private Socket socket;
    private static int stopWay = 1;         // 结束通信的方式
    private final int NATURAL_STOP = 1;     // 自然结束
    private final int SUDDEN_STOP = 2;      // 突然终止程序
    private final int SOCKET_STOP = 3;      // 关闭Socket，再结束程序
    private final int OUTPUT_STOP = 4;      // 关闭输出流，再结束程序
    public SocketDemoSender() throws IOException {
        socket = new Socket(host, port);
    }
    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOS = socket.getOutputStream();   // 获取socket对象的输出流对象
        return new PrintWriter(socketOS, true);
        // PrintWriter中第二个参数true表示：当每写一行，PrintWriter缓存自动溢出，把数据写到目的地
    }
    public void send() throws IOException, InterruptedException {
        PrintWriter pw = getWriter(socket);
        for(int i = 0; i < 20; i++) {
            String msg = "hello_" + i;
            pw.println(msg);
            System.out.println("send: " + msg);
            Thread.sleep(500);  // 睡眠0.5秒
            if(i == 2) {    // 终止程序，结束通信
                if(stopWay == SUDDEN_STOP) {
                    System.out.println("突然终止程序");
                    System.exit(0);
                }
                else if(stopWay == SOCKET_STOP) {
                    System.out.println("关闭Socket并结束程序");
                    socket.close();
                    break;
                }
                else if(stopWay == OUTPUT_STOP) {
                    System.out.println("关闭输出流并结束程序");
                    socket.shutdownOutput();
                    break;
                }
            }
        }
        if(stopWay == NATURAL_STOP)
            socket.close();
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        if(args.length > 0)
            stopWay = Integer.parseInt(args[0]);
        new SocketDemoSender().send();
    }
}
